from db.config import data_path, db, db_all
from common.read_file import read_json
from common.write_file import write_json
from common.utils import empty, init_item

CURRENT_DB_CONFIG = 'current_db_config'


def config_setting(query_model):
    if len(query_model.query_arr) <= query_model.current_index:
        return config_help(query_model)
        pass
    current_key = query_model.query_arr[query_model.current_index]
    if current_key == 'all':
        return get_all_config()
    if current_key == 'current':
        return get_current_config()
    if current_key == 'change_config':
        if len(query_model.query_arr) <= query_model.current_index + 1:
            return init_item(text='请选择要更换的配置')
        set_current_config(query_model.query_arr[query_model.current_index + 1])
        return init_item(text='更换配置成功')
    pass


def config_help(query_model):
    query_prefix = "%s %s " % (query_model.trigger, query_model.query_arr[0])
    results = [
        init_item(
            text='current',
            subtext='返回当前所有配置',
            completion=query_prefix + 'current '
        ),
        init_item(
            text='all',
            subtext='返回当前所有配置',
            completion=query_prefix + 'all '
        ),
    ]
    return results
    pass


def get_current_config(is_query=True):
    data = read_json(data_path)
    if not empty(data) and CURRENT_DB_CONFIG in data and not empty(data[CURRENT_DB_CONFIG]):
        current_config = data[CURRENT_DB_CONFIG]
    else:
        current_config = db
    if not is_query:
        return db
    subtext = "host:%s user:%s password:%s" % (
        current_config['host'], current_config['user'], current_config['password'])
    return init_item(text=current_config['host'], subtext=subtext)
    pass


def get_all_config():
    results = []
    for i in range(len(db_all)):
        config = db_all[i]
        subtext = "host:%s user:%s password:%s" % (config['host'], config['user'], config['password'])
        completion = 'db config change_config ' + str(i)
        results.append(init_item(text=config['host'], subtext=subtext, completion=completion))
    return results
    pass


def set_current_config(index):
    data = read_json(data_path, {})
    data[CURRENT_DB_CONFIG] = db_all[int(index)]
    write_json(data, data_path)
    import db.common.db_map as db_map
    db_map.update_db_map()
    pass
